package cn.iune.erp.inventory;

import java.math.BigDecimal;
import java.sql.Date;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.justep.baas.Utils;
import com.justep.baas.data.Row;
import com.justep.baas.data.RowState;
import com.justep.baas.data.Table;
import com.justep.baas.data.Transform;

import cn.iune.erp.core.BusinessService;

@Transactional
@Service
public class StorageRecordDetailServiceImpl implements IStorageRecordDetailService {
	private final Logger log = LogManager.getLogger(this);

	@Autowired
	private IStorageRecordDetailDao dao;
	
	
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordDetailService#getAll()
	 */
	@Override
	public List<StorageRecordDetail> getAll(){
		return dao.getAll();
	}
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordDetailService#getByID(java.lang.String)
	 */
	@Override
	public StorageRecordDetail getByID(String fID) {
		return dao.getByID(fID);
	}
	
	@Transactional
	@Override
	public void insert(StorageRecordDetail obj) {
		dao.insert(obj);
	}

	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordDetailService#delete(java.lang.String)
	 */
	@Override
	@Transactional
	public void delete(String fID) {
		dao.delete(fID);
	}
	
	@Transactional
	@Override
	public StorageRecordDetail update(StorageRecordDetail obj) {
		return dao.update(obj);
	}

	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordDetailService#getByNo(java.lang.String, java.lang.String, java.lang.String)
	 */
	@Override
	public StorageRecordDetail getByNo(String recordNo, String serialNo, String enterpriseNo) {
		return dao.getByNo(recordNo, serialNo, enterpriseNo);
	}
	
	@Transactional
	@Override
	public JSONObject save(JSONObject object) throws ParseException {
//		System.out.println("StorageRecordDetailServiceImpl。save");
//		System.out.println(object.toJSONString());
		// TODO Auto-generated method stub
		// JSON转换Table
		Table table = Transform.jsonToTable(object);
		
		JSONObject json = new JSONObject();
		json.put("concept", "StorageRecordDetail");
		JSONArray rows = new JSONArray();

		List<Row> list = table.getRows();
		for(Row row : list){
			JSONObject javaObject= Transform.rowToJavaObject(table, row);
//			System.out.println(javaObject.toJSONString());
			StorageRecordDetail obj = JSON.toJavaObject(javaObject, StorageRecordDetail.class);
//			System.out.println("RowState-->"+obj.getRowState());
			if(RowState.NEW.equals(obj.getRowState())){
				dao.insert(obj);
			}
			if(RowState.DELETE.equals(obj.getRowState())){
				dao.delete(obj.getfID());
			}
			if(RowState.EDIT.equals(obj.getRowState())){
				StorageRecordDetail objNew = dao.update(obj);
				JSONObject jsonRow = new JSONObject();
				jsonRow.put("id", obj.getfID());
				jsonRow.put("version", objNew.getVersion());
				rows.add(jsonRow);
			}
		}
		
		json.put("rows", rows);
		
		return json;
		
	}

	@Override
	public JSONObject querySimple(JSONObject data) {
		try {
			return dao.querySimple(data);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
			JSONObject json = new JSONObject();
			json.put("code", -1);
			json.put("msg", "failure");
			return json;
		}
	}
	
	//联合查询
	@Override
	public JSONObject jointSimple(JSONObject data) {
		try {
			return dao.jointSimple(data);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
			JSONObject json = new JSONObject();
			json.put("code", -1);
			json.put("msg", "failure");
			return json;
		}
	}
	

	//借入借出单查询专用
	@Override
	public JSONObject queryJCJR(JSONObject data) {

		try {
			JSONObject jsonTable = dao.jointJCJR(data);
			
			JSONObject json = new JSONObject();
			json.put("code", 0);
			json.put("msg", "success");
			json.put("data", jsonTable);
			
			return json;
		} catch (SQLException e) {
			e.printStackTrace();
			
			JSONObject json = new JSONObject();
			json.put("code", -1);
			json.put("msg", e.getMessage());
			return json;
		}
	}
	
	@Override
	public JSONObject queryZCGL(JSONObject data)  {
		// TODO Auto-generated method stub

		try {
			JSONObject jsonTable = dao.jointZCGL(data);
			
			JSONObject json = new JSONObject();
			json.put("code", 0);
			json.put("msg", "success");
			json.put("data", jsonTable);
			
			return json;
		} catch (SQLException e) {
			e.printStackTrace();
			
			JSONObject json = new JSONObject();
			json.put("code", -1);
			json.put("msg", e.getMessage());
			return json;
		}	}
	
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordDetailService#getByMasterID(java.lang.String)
	 */
	@Override
	public List<StorageRecordDetail> getByMasterID(String fMasterID) {
		return dao.getByMasterID(fMasterID);
	}
/*
	public JSONObject query(JSONObject data) throws Throwable {
		
		// 获取参数
		Object columns = data.getJSONObject("columns"); // 列定义
		String orderBy = data.getString("orderBy"); // 排序
		Integer limit = data.getInteger("limit"); // 分页查询的行数
		Integer offset = data.getInteger("offset"); // 分页查询的行偏移
		String search = data.getString("search"); // 检索关键字
		String filter = data.getString("filter"); // 过滤条件
		String id = data.getString("id");
		String fMasterID = data.getString("fMasterID");

		
		// 存放SQL中的参数值
		List<Object> sqlParams = new ArrayList<Object>();
		// 存放SQL中的过滤条件
		List<String> filters = new ArrayList<String>();
		if (!CommonService.isEmptyString(search)) {
			// 增加过滤条件
			filters.add("recordNo LIKE ? OR originNo LIKE ? OR comments LIKE ?");
			// 检索关键字中如果没有%，则前后自动加%
			search = (search.indexOf("%") != -1) ? search : "%" + search + "%";
			// sqlParams的参数个数和顺序必须与过滤条件的?相匹配 
			for (int i = 0; i < 3; i++) {
				sqlParams.add(search);
			}
		}
		//处理过滤条件
		if (!CommonService.isEmptyString(filter)) {
			filters.add(filter);
		}
		//处理id
		if (!CommonService.isEmptyString(id)) {
			filters.add("fID='"+id+"'");
		}
		//处理fMasterID
//		System.out.println("fMasterID-->"+fMasterID);
		if (!CommonService.isEmptyString(fMasterID)) {
			filters.add("fMasterID='"+fMasterID+"'");
		}
	
		
		Table table = Transform.createTableByColumnsDefine((JSONObject) columns);
		
		if (offset != null && offset.equals(0)) {
			long rowCount = dao.getCount(filters, sqlParams);
			table.setTotal((int)rowCount);
		}

//		String orderBy = "serialNo DESC";
				
		//获取数据
		List<Row> rows = listToRows(dao.query(filters,orderBy,sqlParams,offset,limit));
	    table.appendRows(rows);
		JSONObject json = Transform.tableToJson(table);
	
		return json;
	}

	public int save(JSONObject object) throws Throwable {
		// TODO Auto-generated method stub
//		log.info("@RequestParam------"+object.toJSONString());
		// JSON转换Table
		Table table = Transform.jsonToTable(object);
		List<StorageRecordDetail> list = rowsToList(table.getRows());

		for(StorageRecordDetail obj : list){
			if(RowState.NEW.equals(obj.getRowState())){
				dao.insert(obj);
			}
			if(RowState.EDIT.equals(obj.getRowState())){
				dao.update(obj);
			}
			if(RowState.DELETE.equals(obj.getRowState())){
				dao.delete(obj.getfID());
			}
		}
		return 0;
	}

	public List<Row> listToRows(List<StorageRecordDetail> list){
		//添加行集
		List<Row> rows = new ArrayList<Row>();
		//循环行
	    for(StorageRecordDetail o : list){
	    	rows.add(objectToRow(o));
	    }
	    return rows;
	}

	public List<StorageRecordDetail> rowsToList(List<Row> rows){
		//添加行集
		List<StorageRecordDetail> list = new ArrayList<StorageRecordDetail>();
		//循环行
	    for(Row r : rows){
	    	list.add(rowToObject(r));
	    }
	    return list;
	}

	public Row objectToRow(StorageRecordDetail obj){
    	
		Map<String, ColumnValue> values = new HashMap<String, ColumnValue>();
		//循环行中每一列
		ColumnValue value = new ColumnValue(obj.getfID());
		values.put("fID", value);
		value = new ColumnValue(obj.getSystemCode());
 		values.put("systemCode", value);
		value = new ColumnValue(obj.getBillType());
 		values.put("billType", value);
		value = new ColumnValue(obj.getBillTypeName());
 		values.put("billTypeName", value);
		value = new ColumnValue(obj.getOrderDate());
 		values.put("orderDate", value);
		value = new ColumnValue(obj.getState());
 		values.put("state", value);
		value = new ColumnValue(obj.getStatus());
 		values.put("status", value);
 		
		value = new ColumnValue(obj.getRevOpay());
 		values.put("revOpay", value);
		value = new ColumnValue(obj.getDirection());
 		values.put("direction", value);
		value = new ColumnValue(obj.getCostingCode());
 		values.put("costingCode", value);
		value = new ColumnValue(obj.getAudit());
 		values.put("audit", value);
		value = new ColumnValue(obj.getConfirmDate());
 		values.put("confirmDate", value);

		value = new ColumnValue(obj.getOrigin());
 		values.put("origin", value);
		value = new ColumnValue(obj.getOriginName());
 		values.put("originName", value);
		value = new ColumnValue(obj.getOriginNo());
 		values.put("originNo", value);
 		
		value = new ColumnValue(obj.getRecordNo());
 		values.put("recordNo", value);

		value = new ColumnValue(obj.getFactoryNo());
 		values.put("factoryNo", value);
		value = new ColumnValue(obj.getFactoryName());
 		values.put("factoryName", value);
 		
		value = new ColumnValue(obj.getStorageTypeD());
 		values.put("storageTypeD", value);
		value = new ColumnValue(obj.getStorageTypeDLabel());
 		values.put("storageTypeDLabel", value);
		value = new ColumnValue(obj.getProviderNo());
 		values.put("providerNo", value);
		value = new ColumnValue(obj.getShortName());
 		values.put("shortName", value);
		value = new ColumnValue(obj.getProviderName());
 		values.put("providerName", value);
 		
		value = new ColumnValue(obj.getStorageType());
 		values.put("storageType", value);
		value = new ColumnValue(obj.getStorageTypeLabel());
 		values.put("storageTypeLabel", value);
		value = new ColumnValue(obj.getStorageNo());
 		values.put("storageNo", value);
		value = new ColumnValue(obj.getStorageName());
 		values.put("storageName", value);
		value = new ColumnValue(obj.getFloorNo());
 		values.put("floorNo", value);
 		
		value = new ColumnValue(obj.getTaxType());
 		values.put("taxType", value);
		value = new ColumnValue(obj.getTaxTypeLabel());
 		values.put("taxTypeLabel", value);
		value = new ColumnValue(obj.getTaxRate());
 		values.put("taxRate", value);
		
		value = new ColumnValue(obj.getfMasterID());
 		values.put("fMasterID", value);
		
		value = new ColumnValue(obj.getItemNo());
 		values.put("itemNo", value);
		value = new ColumnValue(obj.getItemDescribe());
 		values.put("itemDescribe", value);
		value = new ColumnValue(obj.getItemProperty());
 		values.put("itemProperty", value);
		value = new ColumnValue(obj.getUnitCode());
 		values.put("unitCode", value);
		value = new ColumnValue(obj.getUnitName());
 		values.put("unitName", value);
		value = new ColumnValue(obj.getProcess());
 		values.put("process", value);
		value = new ColumnValue(obj.getProcessLabel());
 		values.put("processLabel", value);
		
		value = new ColumnValue(obj.getMaterialType());
 		values.put("materialType", value);
		value = new ColumnValue(obj.getMaterialTypeLabel());
 		values.put("materialTypeLabel", value);
		
		value = new ColumnValue(obj.getQualityStatus());
 		values.put("qualityStatus", value);
		value = new ColumnValue(obj.getQualityStatusLabel());
 		values.put("qualityStatusLabel", value);
		
		value = new ColumnValue(obj.getItemPrice());
 		values.put("itemPrice", value);
		value = new ColumnValue(obj.getDiscountRate());
 		values.put("discountRate", value);
		
		value = new ColumnValue(obj.getArriveAmount());
 		values.put("arriveAmount", value);
		value = new ColumnValue(obj.getWasterAmount());
 		values.put("wasterAmount", value);
		value = new ColumnValue(obj.getUllageAmount());
 		values.put("ullageAmount", value);
		value = new ColumnValue(obj.getArriveAmountBack());
 		values.put("arriveAmountBack", value);
		value = new ColumnValue(obj.getPriceAmount());
 		values.put("priceAmount", value);
 		
		value = new ColumnValue(obj.getItemAmount());
 		values.put("itemAmount", value);
		value = new ColumnValue(obj.getOrderAmount());
 		values.put("orderAmount", value);
		value = new ColumnValue(obj.getOrderAmountOld());
 		values.put("orderAmountOld", value);
		value = new ColumnValue(obj.getOrderAmountTax());
 		values.put("orderAmountTax", value);
		value = new ColumnValue(obj.getOrderAmountTotal());
 		values.put("orderAmountTotal", value);
 		
		value = new ColumnValue(obj.getAccountQuantityI());
 		values.put("accountQuantityI", value);
		value = new ColumnValue(obj.getAccountQuantityO());
 		values.put("accountQuantityO", value);
 		
		value = new ColumnValue(obj.getPieceQuantity());
 		values.put("pieceQuantity", value);
		value = new ColumnValue(obj.getPieceQuantityI());
 		values.put("pieceQuantityI", value);
		value = new ColumnValue(obj.getPieceQuantityO());
 		values.put("pieceQuantityO", value);
		value = new ColumnValue(obj.getQuantityL());
 		values.put("quantityL", value);
		value = new ColumnValue(obj.getCostingL());
 		values.put("costingL", value);
		value = new ColumnValue(obj.getAmountL());
 		values.put("amountL", value);
		value = new ColumnValue(obj.getPieceQuantityL());
 		values.put("pieceQuantityL", value);

		value = new ColumnValue(obj.getWasterItemIng());
 		values.put("wasterItemIng", value);
		value = new ColumnValue(obj.getWasterItemAmount());
 		values.put("wasterItemAmount", value);
		value = new ColumnValue(obj.getWasterPiece());
 		values.put("wasterPiece", value);
 		
		value = new ColumnValue(obj.getInvoiceQuantityIng());
 		values.put("invoiceQuantityIng", value);
 		value = new ColumnValue(obj.getInvoiceQuantity());
 		values.put("invoiceQuantity", value);
		value = new ColumnValue(obj.getInvoiceAmount());
 		values.put("invoiceAmount", value);
		
		value = new ColumnValue(obj.getEvaluateQuantityIng());
 		values.put("evaluateQuantityIng", value);
		value = new ColumnValue(obj.getEvaluateQuantity());
 		values.put("evaluateQuantity", value);
		value = new ColumnValue(obj.getEvaluateAmount());
 		values.put("evaluateAmount", value);
 		
		value = new ColumnValue(obj.getBackItemIng());
 		values.put("backItemIng", value);
		value = new ColumnValue(obj.getBackItemAmount());
 		values.put("backItemAmount", value);
		value = new ColumnValue(obj.getBackPiece());
 		values.put("backPiece", value);
		
		value = new ColumnValue(obj.getMaterialAmount());
 		values.put("materialAmount", value);
		value = new ColumnValue(obj.getHumanAmount());
 		values.put("workingAmount", value);
		value = new ColumnValue(obj.getManufactAmount());
 		values.put("manufactAmount", value);
		value = new ColumnValue(obj.getProcessAmount());
 		values.put("processAmount", value);
		value = new ColumnValue(obj.getCostingAmount());
 		values.put("costingAmount", value);
 		
		value = new ColumnValue(obj.getMaterialAmountPer());
 		values.put("materialAmountPer", value);
		value = new ColumnValue(obj.getHumanAmountPer());
 		values.put("workingAmountPer", value);
		value = new ColumnValue(obj.getManufactAmountPer());
 		values.put("manufactAmountPer", value);
		value = new ColumnValue(obj.getProcessAmountPer());
 		values.put("processAmountPer", value);
		value = new ColumnValue(obj.getCostingAmountPer());
 		values.put("costingAmountPer", value);

		value = new ColumnValue(obj.getDevolveCause());
 		values.put("devolveCause", value);
		value = new ColumnValue(obj.getDevolveCauseLabel());
 		values.put("devolveCauseLabel", value);
 		
		value = new ColumnValue(obj.getWorkingHourUsed());
 		values.put("workingHourUsed", value);
		value = new ColumnValue(obj.getMachineHourUsed());
 		values.put("machineHourUsed", value);
 		
		value = new ColumnValue(obj.getDeductAmount());
 		values.put("deductAmount", value);
		value = new ColumnValue(obj.getApportionAmount());
 		values.put("apportionAmount", value);
 		
		value = new ColumnValue(obj.getBrand());
 		values.put("brand", value);
		value = new ColumnValue(obj.getBrandLabel());
 		values.put("brandLabel", value);
		value = new ColumnValue(obj.getPlaceOrigin());
 		values.put("placeOrigin", value);
		value = new ColumnValue(obj.getManufacturer());
 		values.put("manufacturer", value);
		
		value = new ColumnValue(obj.getBatchNo());
 		values.put("batchNo", value);
		value = new ColumnValue(obj.getBatchDescribe());
 		values.put("batchDescribe", value);
		value = new ColumnValue(obj.getProduceDate());
 		values.put("produceDate", value);
		value = new ColumnValue(obj.getValidDate());
 		values.put("validDate", value);
		value = new ColumnValue(obj.getCheckoutAgainDate());
 		values.put("checkoutAgainDate", value);
 		
		value = new ColumnValue(obj.getStoreNo());
 		values.put("storeNo", value);
		value = new ColumnValue(obj.getAbcGrade());
 		values.put("abcGrade", value);
		
		value = new ColumnValue(obj.getItemSize());
 		values.put("itemSize", value);
		value = new ColumnValue(obj.getOrderWeight());
 		values.put("itemWeight", value);
 		
		value = new ColumnValue(obj.getOrderSize());
 		values.put("orderSize", value);
		value = new ColumnValue(obj.getOrderWeight());
 		values.put("orderWeight", value);

		value = new ColumnValue(obj.getWorkNo());
 		values.put("workNo", value);
		value = new ColumnValue(obj.getProcedureStep());
 		values.put("procedureStep", value);
		value = new ColumnValue(obj.getProjectNo());
 		values.put("projectNo", value);
		value = new ColumnValue(obj.getOrderNo());
 		values.put("orderNo", value);
		value = new ColumnValue(obj.getCheckoutTimes());
 		values.put("checkoutTimes", value);
		value = new ColumnValue(obj.getBarCode());
 		values.put("barCode", value);

//		value = new ColumnValue(obj.getDepartmentNo());
// 		values.put("departmentNo", value);
//		value = new ColumnValue(obj.getDepartmentName());
// 		values.put("departmentName", value);
		value = new ColumnValue(obj.getEmployeeNo());
 		values.put("employeeNo", value);
		value = new ColumnValue(obj.getEmployeeName());
 		values.put("employeeName", value);
		
		value = new ColumnValue(obj.getComments());
 		values.put("comments", value);

		value = new ColumnValue(obj.getUserId());
 		values.put("userId", value);
		value = new ColumnValue(obj.getEnterpriseNo());
 		values.put("enterpriseNo", value);
		value = new ColumnValue(obj.getEnterpriseName());
 		values.put("enterpriseName", value);

		value = new ColumnValue(obj.getVersion());
 		values.put("version", value);
		
		Row row = new Row(values,RowState.NONE);
		return row;
	}
	
	public StorageRecordDetail rowToObject(Row row){
		StorageRecordDetail obj = new StorageRecordDetail();
		obj.setfID(row.getString("fID"));
	    
		obj.setSystemCode(row.getString("systemCode"));			
		obj.setBillType(row.getString("billType"));
		obj.setBillTypeName(row.getString("billTypeName"));
		obj.setOrderDate(row.getDate("orderDate"));
		obj.setState(row.getString("state"));
		obj.setStatus(row.getString("status"));

		obj.setRevOpay(row.getString("revOpay"));
		obj.setDirection(row.getInteger("direction"));
		obj.setCostingCode(row.getString("costingCode"));
		obj.setAudit(row.getString("audit"));
		obj.setConfirmDate(row.getDate("confirmDate"));
		
		obj.setOrigin(row.getString("origin"));
		obj.setOriginName(row.getString("originName"));
		obj.setOriginNo(row.getString("originNo"));
		
		obj.setRecordNo(row.getString("recordNo"));
		
		obj.setFactoryNo(row.getString("factoryNo"));
		obj.setFactoryName(row.getString("factoryName"));

		obj.setStorageTypeD(row.getString("storageTypeD"));
		obj.setStorageTypeDLabel(row.getString("storageTypeDLabel"));
		obj.setProviderNo(row.getString("providerNo"));
		obj.setShortName(row.getString("shortName"));
		obj.setProviderName(row.getString("providerName"));
		
		obj.setStorageType(row.getString("storageType"));
		obj.setStorageTypeLabel(row.getString("storageTypeLabel"));
		obj.setStorageNo(row.getString("storageNo"));
		obj.setStorageName(row.getString("storageName"));
		obj.setFloorNo(row.getString("floorNo"));

		obj.setTaxType(row.getInteger("taxType"));
		obj.setTaxTypeLabel(row.getString("taxTypeLabel"));
		obj.setTaxRate(row.getDecimal("taxRate"));
		
		obj.setfMasterID(row.getString("fMasterID"));
		
		obj.setItemNo(row.getString("itemNo"));
		obj.setItemDescribe(row.getString("itemDescribe"));
		obj.setItemProperty(row.getString("itemProperty"));
		obj.setUnitCode(row.getString("unitCode"));
		obj.setUnitName(row.getString("unitName"));
		obj.setProcess(row.getString("process"));
		obj.setProcessLabel(row.getString("processLabel"));
		
		obj.setMaterialType(row.getInteger("materialType"));
		obj.setMaterialTypeLabel(row.getString("materialTypeLabel"));
		
		obj.setQualityStatus(row.getInteger("qualityStatus"));
		obj.setQualityStatusLabel(row.getString("qualityStatusLabel"));

		obj.setItemPrice(row.getDecimal("itemPrice"));
		obj.setDiscountRate(row.getDecimal("discountRate"));
		
		obj.setArriveAmount(row.getDecimal("arriveAmount"));
		obj.setWasterAmount(row.getDecimal("wasterAmount"));
		obj.setUllageAmount(row.getDecimal("ullageAmount"));
		obj.setArriveAmountBack(row.getDecimal("arriveAmountBack"));
		obj.setPriceAmount(row.getDecimal("priceAmount"));
		
		obj.setItemAmount(row.getDecimal("itemAmount"));
		obj.setOrderAmount(row.getDecimal("orderAmount"));
		obj.setOrderAmountOld(row.getDecimal("orderAmountOld"));
		obj.setOrderAmountTax(row.getDecimal("orderAmountTax"));
		obj.setOrderAmountTotal(row.getDecimal("orderAmountTotal"));
		
		obj.setAccountQuantityI(row.getDecimal("accountQuantityI"));
		obj.setAccountQuantityO(row.getDecimal("accountQuantityO"));
		
		obj.setPieceQuantity(row.getDecimal("pieceQuantity"));
		obj.setPieceQuantityI(row.getDecimal("pieceQuantityI"));
		obj.setPieceQuantityO(row.getDecimal("pieceQuantityO"));
		
		obj.setQuantityL(row.getDecimal("quantityL"));
		obj.setAmountL(row.getDecimal("amountL"));
		obj.setCostingL(row.getDecimal("costingL"));
		obj.setPieceQuantityL(row.getDecimal("pieceQuantityL"));
		
		obj.setWasterItemIng(row.getDecimal("wasterItemIng"));
		obj.setWasterItemAmount(row.getDecimal("wasterItemAmount"));
		obj.setWasterPiece(row.getDecimal("wasterPiece"));
		
		obj.setInvoiceQuantityIng(row.getDecimal("invoiceQuantityIng"));
		obj.setInvoiceQuantity(row.getDecimal("invoiceQuantity"));
		obj.setInvoiceAmount(row.getDecimal("invoiceAmount"));

		obj.setEvaluateQuantityIng(row.getDecimal("evaluateQuantityIng"));
		obj.setEvaluateQuantity(row.getDecimal("evaluateQuantity"));
		obj.setEvaluateAmount(row.getDecimal("evaluateAmount"));
		
		obj.setBackItemIng(row.getDecimal("backItemIng"));
		obj.setBackItemAmount(row.getDecimal("backItemAmount"));
		obj.setBackPiece(row.getDecimal("backPiece"));
		
		obj.setMaterialAmount(row.getDecimal("materialAmount"));
		obj.setHumanAmount(row.getDecimal("workingAmount"));
		obj.setManufactAmount(row.getDecimal("manufactAmount"));
		obj.setProcessAmount(row.getDecimal("processAmount"));
		obj.setCostingAmount(row.getDecimal("costingAmount"));
		
		obj.setMaterialAmountPer(row.getDecimal("materialAmountPer"));
		obj.setHumanAmountPer(row.getDecimal("workingAmountPer"));
		obj.setManufactAmountPer(row.getDecimal("manufactAmountPer"));
		obj.setProcessAmountPer(row.getDecimal("processAmountPer"));
		obj.setCostingAmountPer(row.getDecimal("costingAmountPer"));
		
		obj.setDevolveCause(row.getString("devolveCause"));
		obj.setDevolveCauseLabel(row.getString("devolveCauseLabel"));

		obj.setWorkingHourUsed(row.getDecimal("workingHourUsed"));
		obj.setMachineHourUsed(row.getDecimal("machineHourUsed"));

		obj.setDeductAmount(row.getDecimal("deductAmount"));//扣款金额
		obj.setApportionAmount(row.getDecimal("apportionAmount"));//进货费用(分摊)
		
		obj.setBatchNo(row.getString("batchNo"));
		obj.setBatchDescribe(row.getString("batchDescribe"));
		obj.setProduceDate(row.getDate("produceDate"));
		obj.setValidDate(row.getDate("validDate"));
		obj.setCheckoutAgainDate(row.getDate("checkoutAgainDate"));
		
		obj.setBrand(row.getString("brand"));
		obj.setBrandLabel(row.getString("brandLabel"));
		obj.setPlaceOrigin(row.getString("placeOrigin"));
		obj.setManufacturer(row.getString("manufacturer"));

		obj.setStoreNo(row.getString("storeNo"));
		obj.setAbcGrade(row.getString("abcGrade"));
		
		obj.setItemWeight(row.getDecimal("itemWeight"));
		obj.setItemSize(row.getString("itemSize"));

		obj.setOrderWeight(row.getDecimal("orderWeight"));
		obj.setOrderSize(row.getString("orderSize"));
		
		obj.setWorkNo(row.getString("workNo"));
		obj.setProcedureStep(row.getString("procedureStep"));
		obj.setProjectNo(row.getString("projectNo"));
		obj.setOrderNo(row.getString("orderNo"));
		
		obj.setCheckoutTimes(row.getString("checkoutTimes"));
		obj.setBarCode(row.getString("barCode"));
		
		obj.setEmployeeNo(row.getString("employeeNo"));
		obj.setEmployeeName(row.getString("employeeName"));
//		obj.setDepartmentNo(row.getString("departmentNo"));
//		obj.setDepartmentName(row.getString("departmentName"));

		obj.setComments(row.getString("comments"));
		
		obj.setUserId(row.getString("userId"));

		obj.setEnterpriseNo(row.getString("enterpriseNo"));
		obj.setEnterpriseName(row.getString("enterpriseName"));
		
		obj.setVersion(row.getInteger("version"));
		
		obj.setRowState(row.getState());

		return obj;
	}
*/	
	
	
	///////////////////////业务功能///////////////////////////////////////
	

	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordDetailService#getWXPGByStep(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
	 */
	@Override
	public StorageRecordDetail getWXPGByStep(String workNo, String procedureStep, String billType, String enterpriseNo) {
		return dao.getWXPGByStep(workNo, procedureStep, billType, enterpriseNo);
	}
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordDetailService#getWXWGByStep(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
	 */
	@Override
	public StorageRecordDetail getWXWGByStep(String workNo, String procedureStep, String billType, String enterpriseNo) {
		return dao.getWXWGByStep(workNo, procedureStep, billType, enterpriseNo);
	}
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordDetailService#getWXFLByStep(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
	 */
	@Override
	public List<StorageRecordDetail> getWXFLByStep(String workNo, String procedureStep, String billType, String enterpriseNo) {
		return dao.getWXFLByStep(workNo, procedureStep, billType, enterpriseNo);
	}
	
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordDetailService#getOrderLLD(int, java.sql.Date, java.sql.Date, java.lang.String)
	 */
	@Override
	public List<StorageRecordDetail> getCostingLLDList(String workNo, Date dateStart, Date dateEnd, String enterpriseNo) {
		return dao.getCostingLLDList(workNo, dateStart, dateEnd, enterpriseNo);
	}
	
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordDetailService#getOrderRKD(int, java.sql.Date, java.sql.Date, java.lang.String)
	 */
	@Override
	public List<StorageRecordDetail> getCostingRKDList(Date dateStart, Date dateEnd, String enterpriseNo) {
		return dao.getCostingRKDList(dateStart, dateEnd, enterpriseNo);
	}
	
	//成本核算相关的委外单列表
	@Override
	public List<StorageRecordDetail> getCostingWWDList(Date dateStart, Date dateEnd, String enterpriseNo) {
		return dao.getCostingWWDList(dateStart, dateEnd, enterpriseNo);
	}
	
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordDetailService#getOrderRKDByProduceNo(int, java.lang.String, java.sql.Date, java.sql.Date, java.lang.String)
	 */
	@Override
	public List<StorageRecordDetail> getCostingRKDListByWorkNo(Date dateStart, Date dateEnd, String workNo, String enterpriseNo) {
		return dao.getCostingRKDListByWorkNo(dateStart, dateEnd, workNo, enterpriseNo);
	}
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordDetailService#getOrderZYDByOrigin(java.lang.String, java.sql.Date, java.sql.Date, java.lang.String)
	 */
	@Override
	public List<StorageRecordDetail> getOrderZYDByOrigin(String origin, Date dateStart, Date dateEnd, String enterpriseNo) {
		return dao.getOrderZYDByOrigin(origin, dateStart, dateEnd, enterpriseNo);
	}

	
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordDetailService#confirm(java.lang.String)
	 */
	@Transactional
	@Override
	public int confirm(String fID) {
		StorageRecordDetail srd = dao.getByID(fID);
		return this.confirm(srd);
	}
	
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordDetailService#active(java.lang.String)
	 */
	@Transactional
	@Override
	public int active(String fID) {
		StorageRecordDetail srd = dao.getByID(fID);
		return this.active(srd);
	}
	
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordDetailService#confirm(com.iune.erp.inventory.StorageRecordDetail)
	 */
	@Transactional
	@Override
	public int confirm(StorageRecordDetail srd) {
		srd.setState("confirm");
		srd.setResultStatus("审核中");
		dao.update(srd);
		//System.out.println("事务测试-->子表提交完成");
		return 0;
	}
	
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordDetailService#active(com.iune.erp.inventory.StorageRecordDetail)
	 */
	@Transactional
	@Override
	public int active(StorageRecordDetail srd) {
		srd.setState("active");
		srd.setResultStatus("待审核");
		dao.update(srd);
		return 0;
	}

	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordDetailService#deleteByMasterID(java.lang.String)
	 */
	@Transactional
	@Override
	public int deleteByMasterID(String fMasterID){
		List<StorageRecordDetail> srds = dao.getByMasterID(fMasterID);
		for(StorageRecordDetail srd:srds){
			dao.delete(srd.getfID());;
		}
		return 0;
	}

	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordDetailService#confirmByMasterID(java.lang.String)
	 */
	@Transactional
	@Override
	public int confirmByMasterID(String fMasterID){
		List<StorageRecordDetail> srds = dao.getByMasterID(fMasterID);
		for(StorageRecordDetail srd:srds){
			this.confirm(srd);
		}
		return 0;
	}
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordDetailService#activeByMasterID(java.lang.String)
	 */
	@Transactional
	@Override
	public int activeByMasterID(String fMasterID){
		List<StorageRecordDetail> srds = dao.getByMasterID(fMasterID);
		for(StorageRecordDetail srd:srds){
			this.active(srd);
		}
		return 0;
	}

	//审核通过，改变审核状态为confirm
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordDetailService#agreeIt(com.iune.erp.inventory.StorageRecordDetail)
	 */
	@Transactional
	@Override
	public StorageRecordDetail agreeIt(StorageRecordDetail srd) {
		
		srd.setAudit("confirm");
		srd.setConfirmDate(Utils.getCurrentDate());
		
		srd.setResultStatus("已审核");
		dao.update(srd);
		//执行更新操作

//		this.doIt(srd);
		
		return srd;
	}
	
	//审核拒绝，改变审核状态为active
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordDetailService#unAgree(com.iune.erp.inventory.StorageRecordDetail)
	 */
	@Transactional
	@Override
	public StorageRecordDetail unAgree(StorageRecordDetail srd) {

		srd.setAudit("active");
		srd.setConfirmDate(null);
		
		srd.setResultStatus("审核中");
		dao.update(srd);
		//执行更新操作
		
//		this.unDo(srd);

		return srd;
	}
	
	//审核通过，改变审核状态为confirm
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordDetailService#agreeIt(java.lang.String, java.sql.Date)
	 */
	@Transactional
	@Override
	public StorageRecordDetail agreeIt(String fID) {
		StorageRecordDetail srd = dao.getByID(fID);
		return this.agreeIt(srd);
	}
	
	//审核拒绝，改变审核状态为active
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordDetailService#unAgree(java.lang.String)
	 */
	@Transactional
	@Override
	public StorageRecordDetail unAgree(String fID) {
		StorageRecordDetail srd = dao.getByID(fID);
		return this.unAgree(srd);
	}

	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordDetailService#agreeItByMasterID(java.lang.String)
	 */
	@Transactional
	@Override
	public int agreeItByMasterID(String fMasterID){
		List<StorageRecordDetail> srds = dao.getByMasterID(fMasterID);
		for(StorageRecordDetail srd :srds){
			this.agreeIt(srd);
		}
		return 0;
	}
	
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordDetailService#unAgreeByMasterID(java.lang.String)
	 */
	@Transactional
	@Override
	public int unAgreeByMasterID(String fMasterID){
		List<StorageRecordDetail> srds = dao.getByMasterID(fMasterID);
		for(StorageRecordDetail srd :srds){
			this.unAgree(srd);
		}
		return 0;
	}

	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordDetailService#agreeIt(java.util.List, java.sql.Date)
	 */
	@Transactional
	@Override
	public int agreeIt(List<StorageRecordDetail> srds){
		for(StorageRecordDetail srd :srds){
			this.agreeIt(srd);
		}
		return 0;
	}
	
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordDetailService#unAgree(java.util.List)
	 */
	@Transactional
	@Override
	public int unAgree(List<StorageRecordDetail> srds){
		for(StorageRecordDetail srd :srds){
			this.unAgree(srd);
		}
		return 0;
	}
	
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordDetailService#open(java.lang.String)
	 */
	@Transactional
	@Override
	public int open(String fID) {
		StorageRecordDetail srd = dao.getByID(fID);
		return this.open(srd);
	}
	
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordDetailService#close(java.lang.String)
	 */
	@Transactional
	@Override
	public int close(String fID) {
		StorageRecordDetail srd = dao.getByID(fID);
		return this.close(srd);
	}
	
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordDetailService#open(com.iune.erp.inventory.StorageRecordDetail)
	 */
	@Transactional
	@Override
	public int open(StorageRecordDetail srd) {
		srd.setStatus("open");
		dao.update(srd);
		return 0;
	}
	
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordDetailService#close(com.iune.erp.inventory.StorageRecordDetail)
	 */
	@Transactional
	@Override
	public int close(StorageRecordDetail srd) {
		srd.setStatus("close");
		dao.update(srd);
		return 0;
	}

	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordDetailService#openByMasterID(java.lang.String)
	 */
	@Transactional
	@Override
	public int openByMasterID(String fMasterID){
		List<StorageRecordDetail> srds = dao.getByMasterID(fMasterID);
		for(StorageRecordDetail srd:srds){
			this.open(srd);
		}
		return 0;
	}
	
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordDetailService#closeByMasterID(java.lang.String)
	 */
	@Transactional
	@Override
	public int closeByMasterID(String fMasterID){
		List<StorageRecordDetail> srds = dao.getByMasterID(fMasterID);
		for(StorageRecordDetail srd:srds){
			this.close(srd);
		}
		return 0;
	}
	
	

	/*
	public List<StorageRecordDetail> getStorageRecordDetailList(String fMasterID,String billType) {
		return dao.getByMasterID(fMasterID, billType);
	}
	//按转入工序查询厂内维修派工单
	public List<StorageRecordDetail> getStorageRecordDetailInList(String fMasterID,String billType,String procedureStepIn) {
		return dao.getByMasterIDStepIn(fMasterID, billType,procedureStepIn);
	}
	//按转出工序查询厂内维修派工单
	public List<StorageRecordDetail> getStorageRecordDetailOutList(String fMasterID,String billType,String procedureStepOut) {
		return dao.getByMasterIDStepOut(fMasterID, billType, procedureStepOut);
	}
	*/
	
	
	@Transactional
	@Override
	public int updateItemAmount(String fID ,BigDecimal itemAmountNew) {
		StorageRecordDetail storageRecordDetail = dao.getByID(fID);
		
//		int direction = storageRecordDetail.getDirection();
//		BigDecimal bgDirection = new BigDecimal(direction);
		
		//修改数量
		storageRecordDetail.setItemAmount(itemAmountNew);
		storageRecordDetail.setArriveAmount(itemAmountNew);
		storageRecordDetail.setPriceAmount(itemAmountNew);
		//件数
		storageRecordDetail.setPieceQuantity(itemAmountNew);
		
		//计算金额
		JSONObject jsonResult = BusinessService.taxCalculate(storageRecordDetail.getItemAmount(), storageRecordDetail.getItemPrice(), storageRecordDetail.getTaxType(), storageRecordDetail.getTaxRate(), storageRecordDetail.getDiscountRate());
		
		storageRecordDetail.setOrderAmount(jsonResult.getBigDecimal("orderAmount"));
		storageRecordDetail.setOrderAmountOld(jsonResult.getBigDecimal("orderAmountOld"));
		storageRecordDetail.setOrderAmountTax(jsonResult.getBigDecimal("orderAmountTax"));
		storageRecordDetail.setOrderAmountTotal(jsonResult.getBigDecimal("orderAmountTotal"));
		
		//账数量，保留两位小数
//		BigDecimal accountQuantityO = storageRecordDetail.getPriceAmount().multiply(bgDirection);
//		accountQuantityO = accountQuantityO.setScale(2, BigDecimal.ROUND_HALF_UP);
//		storageRecordDetail.setAccountQuantityO(accountQuantityO);
		//件数
//		BigDecimal pieceQuantityO = storageRecordDetail.getPieceQuantity().multiply(bgDirection);
//		pieceQuantityO = pieceQuantityO.setScale(2, BigDecimal.ROUND_HALF_UP);
//		storageRecordDetail.setPieceQuantityO(pieceQuantityO);
		
		//更新子表
		dao.update(storageRecordDetail);
		
		return 0;
	}
	
	/*
	 * "send:已下单"
	 * "start:已开工"//已投产
	 * "ready:已完工"
	 * "ok:已上菜"
	 * 
	 */
	@Transactional
	@Override
	public int updateProcedureStep(String fID, String procedureStep){
		StorageRecordDetail obj = dao.getByID(fID);

		obj.setProcedureStep(procedureStep);
		
		dao.update(obj);
		return 0;
	}
	
	@Transactional
	@Override
	public int updateDevolveCause(String fID, String devolveCause, String devolveCauseLabel){
		StorageRecordDetail obj = dao.getByID(fID);
		obj.setDevolveCause(devolveCause);
		obj.setDevolveCauseLabel(devolveCauseLabel);
		
		dao.update(obj);
		return 0;
	}
	
	/*
	 * 0,"10:待投产"
	 * 1,"11:无需投产"
	 * 2,"12:已投产"
	 * 5,"15:已完工"
	 * 9,"19:已上菜"
	 * 
	 */
	@Transactional
	@Override
	public int updateMaterialType(String fID, int materialType, String materialTypeLabel){
		StorageRecordDetail obj = dao.getByID(fID);
		obj.setMaterialType(materialType);
		obj.setMaterialTypeLabel(materialTypeLabel);
		
		dao.update(obj);
		return 0;
	}
	
	//更新下料尺寸/点餐忌口标签
	@Transactional
	@Override
	public int updateBlankSize(JSONObject data){
		//主表
		String fID = data.getString("id");
		
		StorageRecordDetail obj = dao.getByID(fID);
		//System.out.println("fID-->"+fID);
		
		if(obj==null){
//			jsonobject.put("code", -1);
//			jsonobject.put("status", "订单主表不存在，请检查是否传入ID有误！");
			return -1;
		}
		
//		String cUsercode = data.getString("personCode");
//		String cUsername = data.getString("personName");
//		String userId = data.getString("personID");
		
		String blankSize = data.getString("blankSize");
		
		obj.setBlankSize(blankSize);
		
		dao.update(obj);
		
		return 0;
	}
	
	
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordDetailService#updateCheckoutTimes(com.iune.erp.inventory.StorageRecordDetail, java.lang.String)
	 */
	/*
	@Transactional
	@Override
	public int updateCheckoutTimes(StorageRecordDetail srd,String checkoutTimes, String act){
		srd.setCheckoutTimes(checkoutTimes);
		if(act.equals("afterInsert")){
			srd.setQualityStatus(9);
			srd.setQualityStatusLabel("9:在验");
		}
		if(act.equals("beforeDelete")){
			srd.setQualityStatus(0);
			srd.setQualityStatusLabel("0:待验");
		}
		dao.update(srd);
		return 0;
	}
	*/
	
	@Transactional
	@Override
	public int updateQualityStatus(StorageRecordDetail srd,int qualityStatus,String qualityStatusLabel){
		srd.setQualityStatus(qualityStatus);
		srd.setQualityStatusLabel(qualityStatusLabel);
		dao.update(srd);
		return 0;
	}

	//更新质量检验信息
	
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordDetailService#updateQualityInfo(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.math.BigDecimal, java.math.BigDecimal, java.math.BigDecimal, java.math.BigDecimal, java.math.BigDecimal, java.math.BigDecimal, java.math.BigDecimal, java.sql.Date, java.sql.Date, int, java.lang.String)
	 */
	@Transactional
	@Override
	public int updateQualityInfo(
			String audit  //指明是审核动作（confirm）还是撤销审核（active）
			,String checkoutTimes
			,String recordNo
			,String serialNo
			,String billType
			,String enterpriseNo			
			,BigDecimal arriveAmount
			,BigDecimal itemAmount
			,BigDecimal wasterAmount
			,BigDecimal ullageAmount
			,BigDecimal arriveAmountBack
			,BigDecimal priceAmount
			,BigDecimal pieceQuantity
			,Date validDate
			,Date checkoutAgainDate
			,int qualityStatus
			,String qualityStatusLabel
			){
		//更新数据库出库成本
		StorageRecordDetail srd = dao.getByNo(recordNo, serialNo, enterpriseNo);
//		System.out.println("billType-->"+billType);
//		System.out.println("enterpriseNo-->"+enterpriseNo);
//		System.out.println("wasterAmount-->"+wasterAmount);
		
		if(audit.equals("active") && srd.getAudit().equals("confirm")){
//			throw new RuntimeException("物品已入库，单据无法撤销！");
			return -1;
		}
		
		//出库单位成本
		
		//检验结果数据
		//srd.setArriveAmount(arriveAmount);//到货数量无需修改，也不允许修改。
		
		srd.setItemAmount(itemAmount);  
		srd.setWasterAmount(wasterAmount);
		srd.setUllageAmount(ullageAmount);
		srd.setArriveAmountBack(arriveAmountBack);
		srd.setPriceAmount(priceAmount);
		srd.setPieceQuantity(pieceQuantity);
//		srd.setValidDate(validDate);
//		srd.setCheckoutAgainDate(checkoutAgainDate);
		srd.setQualityStatus(qualityStatus);
		srd.setQualityStatusLabel(qualityStatusLabel);
		
		//数量
		/////////////////////////处理数量//////////////////////////////////////////
		/*
		if (srd.getRevOpay().equals("I") ){
			if (srd.getDirection() == 1){
				srd.setAccountQuantityI(itemAmount);
				srd.setPieceQuantityI(pieceQuantity);
			}
			if (srd.getDirection() == -1){
				srd.setAccountQuantityI(itemAmount.negate());
				srd.setPieceQuantityI(pieceQuantity.negate());
			}
		}
		if (srd.getRevOpay().equals("O")){
			if (srd.getDirection() == 1){
				srd.setAccountQuantityO(itemAmount);
				srd.setPieceQuantityO(pieceQuantity);
			}
			if (srd.getDirection() == -1){
				srd.setAccountQuantityO(itemAmount.negate());
				srd.setPieceQuantityO(pieceQuantity.negate());
			}
		}
		if (srd.getRevOpay().equals("-")){
			if (srd.getDirection() == 1){
				srd.setAccountQuantityI(itemAmount);
				srd.setAccountQuantityO(itemAmount);
				srd.setPieceQuantityI(pieceQuantity);
				srd.setPieceQuantityO(pieceQuantity);
			}
			if (srd.getDirection() == -1){
				srd.setAccountQuantityI(itemAmount.negate());
				srd.setAccountQuantityO(itemAmount.negate());
				srd.setPieceQuantityI(pieceQuantity.negate());
				srd.setPieceQuantityO(pieceQuantity.negate());
			}
		}
		*/
		/////////////////////////////////////////////////////////////////////////
		//金额（不分正负），计价数量会影响
		BigDecimal orderAmount = BigDecimal.ZERO;
		BigDecimal orderAmountOld = BigDecimal.ZERO;
		BigDecimal orderAmountTax = BigDecimal.ZERO;
		BigDecimal orderAmountTotal = BigDecimal.ZERO;
		//1、计算单据金额，无论单价是否含税；
		orderAmount = srd.getItemPrice().multiply(priceAmount);
		orderAmount = orderAmount.divide(BigDecimal.ONE, 2, BigDecimal.ROUND_HALF_UP);
		//2、根据单价是否含税的情况，计算出未税金额和税额；
		int taxType = srd.getTaxType();
		BigDecimal taxRate = srd.getTaxRate();
		if (taxType == -1) {
			// -1.免税
			orderAmountOld = orderAmount;
			orderAmountTax = BigDecimal.ZERO;
		}
		if (taxType == 0) {
			// 0.应税外加
			orderAmountOld = orderAmount;
			orderAmountTax = orderAmountOld.multiply(taxRate);
			orderAmountTax = orderAmountTax.divide(BigDecimal.ONE, 2, BigDecimal.ROUND_HALF_UP);
		}
		if (taxType == 1) {
			// 1.应税内含
			orderAmountOld = orderAmount.divide(BigDecimal.ONE.add(taxRate), 2, BigDecimal.ROUND_HALF_UP);
			orderAmountTax = orderAmount.subtract(orderAmountOld);
		}

		//3、计算出价税合计
		orderAmountTotal = orderAmountOld.add(orderAmountTax);
		////////////////////////////////////////////////////////////////////////////
		
		srd.setOrderAmount(orderAmount);
		srd.setOrderAmountOld(orderAmountOld);
		srd.setOrderAmountTax(orderAmountTax);
		srd.setOrderAmountTotal(orderAmountTotal);
		
		///////////////////////////////////////////////////////////////////////////////
//		DecimalFormat df2=new DecimalFormat("0.00"); //格式化，保留两位小数
//		DecimalFormat df6=new DecimalFormat("0.000000"); //格式化，保留六位小数
//		srd.setMaterialAmountPer(costingAmountPer);
//		srd.setMaterialAmount(costingAmount);
//		srd.setCostingAmountPer(costingAmountPer);
//		System.out.println("srd.getWasterAmount()-->"+srd.getWasterAmount());
		dao.update(srd);

		//如果是维修单，需要更新维修单和报修单的有效日期，即保修期
		
		return 0;
	}
	
	//更新废品报废入库数量
	/*
	public int updateWasterAmount(			
			String serialNo
			,String billType
			,String enterpriseNo			
			,BigDecimal wasterAmount
			, BigDecimal pieceQuantity){
		
		StorageRecordDetail srd = dao.getByNo(serialNo, billType, enterpriseNo);
		//新值保留
		//更新数据库数量
		srd.setWasterAmount(srd.getWasterAmount().add(wasterAmount));
		
		srd.setItemAmount(srd.getItemAmount().subtract(wasterAmount));
		srd.setPieceQuantity(srd.getPieceQuantity().subtract(pieceQuantity));
		
		//判断是入库还是出库
		if (srd.getRevOpay().equals("I")){
			srd.setAccountQuantityI(srd.getAccountQuantityI().subtract(wasterAmount));
			srd.setPieceQuantityI(srd.getPieceQuantityI().subtract(pieceQuantity));
		}
		if (srd.getRevOpay().equals("O")){
			srd.setAccountQuantityO(srd.getAccountQuantityO().subtract(wasterAmount));
			srd.setPieceQuantityO(srd.getPieceQuantityO().subtract(pieceQuantity));
		}
		if (srd.getRevOpay().equals("-")){
			srd.setAccountQuantityI(srd.getAccountQuantityI().subtract(wasterAmount));
			srd.setAccountQuantityO(srd.getAccountQuantityO().subtract(wasterAmount));
			srd.setPieceQuantityI(srd.getPieceQuantityI().subtract(pieceQuantity));
			srd.setPieceQuantityO(srd.getPieceQuantityO().subtract(pieceQuantity));
		}
		dao.update(srd);
		//由于合格数量变化，连带影响入出库数量（还有件数）
		return 0;
	}	
	*/

	//更新正在开票数量
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordDetailService#updateInvoiceItemQuantityIng(java.lang.String, java.lang.String, java.lang.String, java.math.BigDecimal)
	 */
	@Transactional
	@Override
	public int updateInvoiceItemQuantityIng(
			String recordNo
			,String serialNo
			,String enterpriseNo			
			,BigDecimal invoiceQuantity
			){
		
//		System.out.println("enterpriseNo-->"+enterpriseNo);
//		System.out.println("invoiceQuantity-->"+invoiceQuantity);
		StorageRecordDetail srd = dao.getByNo(recordNo, serialNo, enterpriseNo);
//		System.out.println("srd-->"+srd);
		if(srd!=null) {
			//新值保留
			srd.setInvoiceQuantityIng(srd.getInvoiceQuantityIng().add(invoiceQuantity));
			dao.update(srd);
		}
		return 0;
	}	
	
	//采购开票数量和成本
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordDetailService#updateInvoiceItemQuantity(java.lang.String, java.lang.String, java.lang.String, java.math.BigDecimal, java.math.BigDecimal, java.math.BigDecimal)
	 */
	@Transactional
	@Override
	public int updateInvoiceItemQuantity(
			String recordNo
			,String serialNo
			,String enterpriseNo			
			,BigDecimal invoiceQuantity
			,BigDecimal costingAmount//采购成本
			){
		
		StorageRecordDetail srd = dao.getByNo(recordNo, serialNo, enterpriseNo);
		if(srd!=null) {
			
			//新值保留
			srd.setInvoiceQuantityIng(srd.getInvoiceQuantityIng().subtract(invoiceQuantity));
			srd.setInvoiceQuantity(srd.getInvoiceQuantity().add(invoiceQuantity));
			if(srd.getInvoiceQuantity().add(srd.getEvaluateQuantity()).compareTo(srd.getPriceAmount())==0) {
				//已经完成开票
				srd.setInvoiceFlag(1);
			}
			
			//采购成本
			//采购成本在应付管理模块中操作
			//更新采购进货单单的开票成本（实际成本）
			//开票或者暂估数量是否等于计价数量，等于：已经完成开票，等于0：首次开票，否则：部分开票
			//***暂估金额也要写入采购成本
			srd.setInvoiceAmount(srd.getInvoiceAmount().add(costingAmount));
			
			dao.update(srd);
			//////////////////////////////////////////////////////////////////////////////////
	
		}

		return 0;
	}
	
	//更新销售开票数量
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordDetailService#updateInvoiceItemQuantity(java.lang.String, java.lang.String, java.lang.String, java.math.BigDecimal, java.math.BigDecimal, java.math.BigDecimal)
	 */
	@Transactional
	@Override
	public int updateInvoiceItemQuantity(
			String recordNo
			,String serialNo
			,String enterpriseNo			
			,BigDecimal invoiceQuantity
			){
		
		StorageRecordDetail srd = dao.getByNo(recordNo, serialNo, enterpriseNo);
		if(srd!=null) {
			
			//新值保留
			srd.setInvoiceQuantityIng(srd.getInvoiceQuantityIng().subtract(invoiceQuantity));
			srd.setInvoiceQuantity(srd.getInvoiceQuantity().add(invoiceQuantity));
			if(srd.getInvoiceQuantity().add(srd.getEvaluateQuantity()).compareTo(srd.getPriceAmount())==0) {
				//已经完成开票
				srd.setInvoiceFlag(1);
			}
			
			dao.update(srd);
			//////////////////////////////////////////////////////////////////////////////////
	
		}

		return 0;
	}
	
	//更新正在暂估数量
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordDetailService#updateEvaluateItemQuantityIng(java.lang.String, java.lang.String, java.lang.String, java.math.BigDecimal)
	 */
	@Transactional
	@Override
	public int updateEvaluateItemQuantityIng(
			String recordNo
			,String serialNo
			,String enterpriseNo			
			,BigDecimal evaluateQuantity
			){
		
		StorageRecordDetail srd = dao.getByNo(recordNo, serialNo, enterpriseNo);
		//新值保留
		srd.setEvaluateQuantityIng(srd.getEvaluateQuantityIng().add(evaluateQuantity));
		dao.update(srd);

		return 0;
	}	
	//更新暂估数量
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordDetailService#updateEvaluateItemQuantity(java.lang.String, java.lang.String, java.lang.String, java.math.BigDecimal, java.math.BigDecimal)
	 */
	@Transactional
	@Override
	public int updateEvaluateItemQuantity(
			String recordNo
			,String serialNo
			,String enterpriseNo			
			,BigDecimal evaluateQuantity
			,BigDecimal costingAmount//采购成本
			){
		
		StorageRecordDetail srd = dao.getByNo(recordNo, serialNo, enterpriseNo);
		if(srd!=null) {

			//新值保留
			srd.setEvaluateQuantityIng(srd.getEvaluateQuantityIng().subtract(evaluateQuantity));
			srd.setEvaluateQuantity(srd.getEvaluateQuantity().add(evaluateQuantity));
			if(srd.getInvoiceQuantity().add(srd.getEvaluateQuantity()).compareTo(srd.getPriceAmount())==0) {
				//已经完成开票
				srd.setInvoiceFlag(1);
			}
			
			//采购成本
			//采购成本在应付管理模块中操作
			//更新采购进货单单的开票成本（实际成本）
			//开票或者暂估数量是否等于计价数量，等于：已经完成开票，等于0：首次开票，否则：部分开票
			//***暂估金额也要写入采购成本
			srd.setInvoiceAmount(srd.getInvoiceAmount().add(costingAmount));
	
			dao.update(srd);
			//////////////////////////////////////////////////////////////////////////////////
		
		}

		return 0;
	}

	//更新正在处理废品数量
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordDetailService#updateWasterItemQuantityIng(java.lang.String, java.lang.String, java.lang.String, java.math.BigDecimal)
	 */
	@Transactional
	@Override
	public int updateWasterItemQuantityIng(
			String recordNo
			,String serialNo
			,String billType
			,String enterpriseNo			
			,BigDecimal itemQuantity
			){
		
		StorageRecordDetail srd = dao.getByNo(recordNo, serialNo, enterpriseNo);
		//新值保留
		srd.setWasterItemIng(srd.getWasterItemIng().add(itemQuantity));
		dao.update(srd);
		
		return 0;
	}	
	
	//更新处理废品数量
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordDetailService#updateWasterItemQuantity(java.lang.String, java.lang.String, java.lang.String, java.math.BigDecimal, java.math.BigDecimal)
	 */
	@Transactional
	@Override
	public int updateWasterItemQuantity(
			String recordNo
			,String serialNo
			,String billType
			,String enterpriseNo			
			,BigDecimal itemQuantity
			,BigDecimal pieceQuantity
			){
		
		StorageRecordDetail srd = dao.getByNo(recordNo, serialNo, enterpriseNo);
		//新值保留
		srd.setWasterItemIng(srd.getWasterItemIng().subtract(itemQuantity));
		srd.setWasterItemAmount(srd.getWasterItemAmount().add(itemQuantity));
		srd.setWasterPiece(srd.getWasterPiece().add(pieceQuantity));
		dao.update(srd);

		return 0;
	}
	
	//更新正在退库数量
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordDetailService#updateBackItemQuantityIng(java.lang.String, java.lang.String, java.lang.String, java.math.BigDecimal, java.math.BigDecimal, java.math.BigDecimal, java.math.BigDecimal)
	 */
	@Transactional
	@Override
	public int updateBackItemQuantityIng(
			String recordNo
			,String serialNo
			,String billType
			,String enterpriseNo			
			,BigDecimal itemQuantity
			,BigDecimal wasterQuantity
			,BigDecimal ullageQuantity
			,BigDecimal arriveQuantityBack
			){
		
		BigDecimal arriveQuantity = itemQuantity.add(wasterQuantity).add(ullageQuantity).add(arriveQuantityBack);

		StorageRecordDetail srd = dao.getByNo(recordNo, serialNo, enterpriseNo);
		//新值保留
		srd.setBackItemIng(srd.getBackItemIng().add(arriveQuantity));
		dao.update(srd);
		/*
		//更新主表 
//		IStorageRecordService sru = new StorageRecordUtil();
		int updateResult=storageRecordService.updateBackItemQuantityIng(srd.getfMasterID(), itemQuantity);
		if (updateResult<0){
			return -1;
		}
		*/
		
		return 0;
	}	
	
	//更新退库数量
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordDetailService#updateBackItemQuantity(java.lang.String, java.lang.String, java.lang.String, java.math.BigDecimal, java.math.BigDecimal, java.math.BigDecimal, java.math.BigDecimal, java.math.BigDecimal)
	 */
	@Transactional
	@Override
	public int updateBackItemQuantity(
			String recordNo
			,String serialNo
			,String billType
			,String enterpriseNo			
			,BigDecimal itemQuantity
			,BigDecimal wasterQuantity
			,BigDecimal ullageQuantity
			,BigDecimal arriveQuantityBack
			,BigDecimal pieceQuantity
			){
		
		BigDecimal arriveQuantity = itemQuantity.add(wasterQuantity).add(ullageQuantity).add(arriveQuantityBack);
		
		StorageRecordDetail srd = dao.getByNo(recordNo, serialNo, enterpriseNo);
		//新值保留
		srd.setBackItemIng(srd.getBackItemIng().subtract(arriveQuantity));
		srd.setBackItemAmount(srd.getBackItemAmount().add(itemQuantity));
		srd.setBackPiece(srd.getBackPiece().add(pieceQuantity));
		dao.update(srd);
		
		/*
		//更新主表 
//		IStorageRecordService sru = new StorageRecordUtil();
		int updateResult=storageRecordService.updateBackItemQuantity(srd.getfMasterID(), itemQuantity, pieceQuantity);
		if (updateResult<0){
			return -1;
		}
		*/

		return 0;
	}
	
	
	
	//做为主表，组合单/拆解单/维修单等等等等
	@Override
	public StorageRecordDetail packing(
			String billType
			,String billTypeName 
//			,String systemCode 
//			,int flowType 
			,String revOpay 
			,int direction 
			,String costingCode 
			,String autoCode 
			,String origin 
			,String originName 
			,String billNo 

			,String userId //= com.justep.system.context.ContextHelper.getOperator().getID();
			,String enterpriseNo //= this.getEnterpriseNo();
			,String enterpriseName //= this.getEnterpriseName();
			){
		
		String APPID = "21689dc62c7683311307432c2dd34e4d";

		StorageRecordDetail obj = new StorageRecordDetail();
		String fID = Utils.getUUID();
		obj.setfID(fID);
		//单号
		/*
		Map<String,Object> map = usercenterService.getBillParam(billType, enterpriseNo);
		String billTypeName = (String) map.get("billTypeName");
//		String systemCode = (String) map.get("systemCode");
//		int flowType = (int) map.get("flowType");
		String revOpay = (String) map.get("revOpay");
		int direction = (int) map.get("direction");
		String costingCode = (String) map.get("costingCode");
		String autoCode = (String) map.get("autoCode");
		String origin = (String) map.get("origin");
		String originName = (String) map.get("originName");
		if("Y".equals(autoCode)){
			String billNo = (String) map.get("billNo");
			obj.setRecordNo(billNo);
		}
		*/
		if("Y".equals(autoCode)){
			obj.setRecordNo(billNo);
		}
		
		obj.setBillType(billType);
		obj.setBillTypeName(billTypeName);
		obj.setSystemCode(APPID);
//		obj.setFlowType(flowType);
		obj.setRevOpay(revOpay);
		obj.setDirection(direction);
		obj.setCostingCode(costingCode);
		obj.setOrigin(origin);
		obj.setOriginName(originName);
		
		obj.setState("active");
		obj.setStatus("open");
		obj.setAudit("active");
		obj.setOrderDate(Utils.getCurrentDate());
		
		obj.setComments("由客户订单自动生成");
		
//		obj.setcUsercode(cUsercode);
//		obj.setcUsername(cUsername);
//		obj.setcDatetime(Utils.getCurrentDateTime());
		obj.setUserId(userId);
		obj.setEnterpriseNo(enterpriseNo);
		obj.setEnterpriseName(enterpriseName);
		
//		obj.setDetailsCount(0);
//		obj.setDetailsCountState(0);
//		obj.setMaxDetailNo(0);
		
		obj.setVersion(0);
		
		return obj;
	}

	@Override
	public StorageRecordDetail packing(StorageRecord storageRecord){
		StorageRecordDetail obj = new StorageRecordDetail();
		String fID = Utils.getUUID();
		obj.setfID(fID);
		
		obj.setBillType(storageRecord.getBillType());
		obj.setBillTypeName(storageRecord.getBillTypeName());
		obj.setSystemCode(storageRecord.getSystemCode());
		obj.setRevOpay(storageRecord.getRevOpay());
		obj.setDirection(storageRecord.getDirection());
		obj.setDealType(storageRecord.getDealType());
		obj.setCostingCode(storageRecord.getCostingCode());
		obj.setOrigin(storageRecord.getOrigin());
		obj.setOriginName(storageRecord.getOriginName());
		
		obj.setState(storageRecord.getState());
		obj.setStatus(storageRecord.getStatus());
		obj.setAudit(storageRecord.getAudit());
		obj.setOrderDate(storageRecord.getOrderDate());
		
		obj.setfMasterID(storageRecord.getfID());
		obj.setRecordNo(storageRecord.getRecordNo());
		//子表明细号
		int maxDetailNo = storageRecord.getMaxDetailNo() + 1;
		String serialNo = String.format("%05d", maxDetailNo);
		obj.setSerialNo(serialNo);
		
		obj.setFactoryID(storageRecord.getFactoryID());
		obj.setFactoryNo(storageRecord.getFactoryNo());
		obj.setFactoryName(storageRecord.getFactoryName());
		
		obj.setEmployeeNo(storageRecord.getEmployeeNo());
		obj.setEmployeeName(storageRecord.getEmployeeName());
		
		obj.setStorageTypeD(storageRecord.getStorageTypeD());
		obj.setStorageTypeDLabel(storageRecord.getStorageTypeDLabel());
		obj.setProviderID(storageRecord.getProviderID());
		obj.setProviderNo(storageRecord.getProviderNo());
		obj.setShortName(storageRecord.getShortName());
		obj.setProviderName(storageRecord.getProviderName());
		
		obj.setQualityType(0);
		obj.setQualityTypeLabel("0:免检");
		
		obj.setQualityStatus(0);
		obj.setQualityStatusLabel("0.免检");
		
//		obj.setMaterialType(1);
//		obj.setMaterialTypeLabel("1.直接材料");
		
//		obj.setDevolveCause(devolveCause);
//		obj.setDevolveCauseLabel(devolveCauseLabel);
		
		obj.setStorageType(storageRecord.getStorageType());
		obj.setStorageTypeLabel(storageRecord.getStorageTypeLabel());
		obj.setStorageID(storageRecord.getStorageID());
		obj.setStorageNo(storageRecord.getStorageNo());
		obj.setStorageName(storageRecord.getStorageName());
		obj.setFloorNo(storageRecord.getFloorNo());
		
		obj.setTaxType(storageRecord.getTaxType());
		obj.setTaxTypeLabel(storageRecord.getTaxTypeLabel());
		obj.setTaxRate(storageRecord.getTaxRate());
		
		obj.setOrderNo(storageRecord.getOrderNo());
		
		obj.setUserId(storageRecord.getUserId());
		obj.setEnterpriseNo(storageRecord.getEnterpriseNo());
		obj.setEnterpriseName(storageRecord.getEnterpriseName());
		
		obj.setVersion(0);
		
		return obj;
	}
	
	
	////////////////////做为主表时使用//////////////////////////////////////
	
	@Override
	public JSONObject newData(JSONObject data) {
		return dao.create(data);
	}
	
	@Override
	public JSONObject deleteData(JSONObject param) {
//		String ucode = param.getString("ucode");
//		String uname = param.getString("uname");
//		String uid = param.getString("uid");
		
		JSONArray ids = param.getJSONArray("ids");
		for(int i=0;i<ids.size();i++){
			String id = ids.getString(i);
			//这里可以增加是否可删除的判断

			//然后删除主表
			dao.delete(id);
		}

		JSONObject data = new JSONObject();
		data.put("ids", ids);
		
		JSONObject json = new JSONObject();
		json.put("code", 0);
		json.put("msg", "success");
		json.put("data", data);
		
		return json;
	}

	@Override
	public JSONObject saveData(JSONObject param) {
		// TODO Auto-generated method stub
		JSONObject data;
		try {
			//保存主表
			data = this.save(param);
			
			JSONObject json = new JSONObject();
			json.put("code", 0);
			json.put("msg", "success");
			json.put("data", data);
			
			return json;
			
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			log.info("开始打印ParseException");
			e.printStackTrace();
			log.info("e.getMessage()-->>"+e.getMessage());
			log.info("完成打印ParseException");
			
			JSONObject json = new JSONObject();
			json.put("code", -1);
			json.put("msg", e.getMessage());
			
			return json;
		} 
	}

	@Override
	public JSONObject queryData(JSONObject param) {
		// TODO Auto-generated method stub
		try {
			JSONObject jsonTable = dao.query(param);
			
			JSONObject json = new JSONObject();
			json.put("code", 0);
			json.put("msg", "success");
			json.put("data", jsonTable);
			
			return json;
		} catch (SQLException e) {
			e.printStackTrace();
			
			JSONObject json = new JSONObject();
			json.put("code", -1);
			json.put("msg", e.getMessage());
			return json;
		}
	}
	@Override
	public JSONObject validData(JSONObject param) {
		// TODO Auto-generated method stub
		return null;
	}
	
	

	@Override
	public List<StorageRecordDetail> getListByItemID(String itemID, Date dateStart, Date dateEnd,	String enterpriseNo) {
		return dao.getListByItemID(itemID, dateStart, dateEnd, enterpriseNo);
	}

	@Override
	public List<StorageRecordDetail> getList(Date dateStart, Date dateEnd,	String enterpriseNo) {
		return dao.getList(dateStart, dateEnd, enterpriseNo);
	}
	
	
	
	
	
}
